#!/bin/sh
#---------------------------------------------------------------------------------
# restorehdr.sh
# 
# This shell script is invoked to perform a copy of a remote server's HMC critical
# backup archive file (HMCBackup*.tgz) to this HMC's /dump directory.
#
# Based on the arguements passed into this program, the program will attempt to
# either mount a remote system or ftp from that system.
# 
# Usage: restorehdr <type>         (0 = NFS/Samba, 1 = ftp)
#                   <archive name> (HMCBackup*.tgz)
#
#                   if type 0...
#                   <server>        (remote server name)
#                   <resource>      (remote server resource)
#                   <fstype>        (file system type)
#                   <options>       (other 'mount' command options)
#
#                   if type 1...
#                   <server>        (remote ftp server)
#                   <userID>        (userID for ftp access)
#                   <password>      (password for ftp access)
#
# Return Codes:
# 1 - Error locating required backup directory
# 2 - error with portmap
# 3 - Error unmounting the media
# 4 - Media is write-protected
# 5 - Error mounting the media
# 6 - Other errors ('tar' command error)

#---------------------------------------------------------------------------------
# directory and filename which records the backup actions.
#---------------------------------------------------------------------------------
LOGDIR=/var/hsc/log
LOG=$LOGDIR/restorehdr.log
   
LOG_ERROR_LOG=/tmp/restorehdr.log
MOUNT_OUTPUT=/tmp/mountInfo



# common exit point for script
exit_cleanup() {
    rm -f $MOUNT_OUTPUT
    
    # this temp working file may or may not exist. Ensure it is removed prior to exiting
    rm -f /tmp/ftp.log
    
    if [ $1 -eq 0 ]; then
        # set indicator flag file noting a restore should be done on next reboot
        mount /mnt/upgrade
        if [ $? -ne 0 ]; then
	    echo "unable to mount upgrade partiton to set indicator file, rc = $?" >> $LOG
            exit 99
        else
            # ensure this indicator file jives with what is in the main 'restore' script
            touch /mnt/upgrade/rmtbcrit.dat
            if [ $? -ne 0 ]; then
	        echo "unable to 'touch' remote restore indicator file, rc = $?" >> $LOG
                exit 99
            else
	        echo "indicator file correctly set for restore script processing on next reboot." >> $LOG
            fi
            umount /mnt/upgrade
        fi
	echo "Offload of critical system data to this HMC completed successfully on `date`." >> $LOG
    else
	echo "Offload of critical system data completed (with errors) on `date`." >> $LOG
        exit 99
    fi
    exit $1
}  


#---------------------------------------------------------------------------------
# offload dump to mounted server
#---------------------------------------------------------------------------------
function copyMountToDump {

    DIR=$1
    FILE=$2
    SERVER=$3
    RESOURCE=$4
    FSTYPE=$5
    OPTIONS=$6
    funcRC=0
    
    # set local mount point - this directory on the HMC should be established by now
    MTPT=/mnt/remote
    
    # attempt to mount
    # NFS example:
    #   mount -o vers=2 -o proto=udp <server>:<resource> <mount point>
    # Samba example:
    #   mount -t smbfs -o username=xxx,password=yyy //<server>/<resource> <mount point>
    mount $OPTIONS $SERVER:$RESOURCE $MTPT
    mountRC=$?
    if [ $mountRC -eq 0 ]; then
        echo "successful mounting the remote server, continuing..." >> $LOG
        cp $MTPT/$FILE $DIR
        RC=$?
        if [ $RC -eq 0 ]; then
            echo "successful copying the remote backup archive file from mounted system to the HMC." >> $LOG
            funcRC=0
        else
            echo "an error occurred while copying the backup archive file from the remote server, rc=$RC." >> $LOG
            funcRC=11
        fi
    else
        # unable to mount
        echo "an error occurred while attempting to mount the remote system, rc=$mountRC." >> $LOG
        funcRC=10
    fi
        
    umount $MTPT
    echo "exiting copyMountToDump, funcRC = $funcRC." >> $LOG
    return $funcRC
}  



#---------------------------------------------------------------------------------
# offload dump to ftp
#---------------------------------------------------------------------------------
function ftpServerToDump {

    DIR=$1
    FILE=$2
    SERVER=$3
#   CUR_DIR=$4
    USER=$4
    PASSWORD=$5
    
    # change dir to $TESTDIR
    cd $DIR
    
    /usr/kerberos/bin/ftp -n -u $SERVER <<EOF 2>&1 > /tmp/ftp.log
user $USER $PASSWORD
bin
get $FILE
quit
EOF

   # save rc for return
   grep -i "failed" /tmp/ftp.log
   if [ $? -ne 0 ]; then
       # try looking for this
       grep -i "unknown" /tmp/ftp.log
       if [ $? -ne 0 ]; then
           # try looking for this
           grep -i "cannot" /tmp/ftp.log
           if [ $? -ne 0 ]; then
               echo "success ftp'ing the remote backup archive file from remote system." >> $LOG
               funcRC=0
           else
               echo "the keyword <cannot> was detected in the ftp response." >> $LOG
               funcRC=23
           fi
       else
           echo "the keyword <unknown> was detected in the ftp response." >> $LOG
           funcRC=22
       fi
   else
       echo "the keyword <failed> was detected in the ftp response." >> $LOG
       funcRC=21
   fi
   
   # switch back to original directory
   cd -
   
   echo "exiting ftpServerToDump, funcRC = $funcRC." >> $LOG
   return $funcRC
}  



# --------------  End Subroutines --------------------------------------------



# --------------- BEGIN MAIN PROGRAM  ----------------------------------------

#
# Just in case we have NLS troubles reading system information...
#
LANG=en_US
export LANG

#---------------------------------------------------------------------------------
# mount point: the mount point for the media to which the backup is to be stored
# ??? - this must be changed to mount point for DVD RAM
# mountpoint for DVD-RAM now defined (yes, it really is to /media/cdrom. 'fstab'
# entry wil automount correct physical device) 4/25/01 - SLF
#---------------------------------------------------------------------------------
DVD_MOUNTPOINT=/media/cdrom

#---------------------------------------------------------------------------------
# the restore type and the HMC backup archive filename
#---------------------------------------------------------------------------------
RESTORE_TYPE=$1
ARCHIVE=$2
DUMP_DIR=/dump

# Check if the directory for the log file exists.
if [ ! -d $LOGDIR ]; then
	echo "=================================================================" > $LOG_ERROR_LOG
	echo -e "Restore task log for `date`." >> $LOG_ERROR_LOG
	echo "Restore task log directory, <$LOGDIR>, does not exist. Program exiting" >> $LOG_ERROR_LOG
	exit 1
fi

# Start log to record backup actions.
echo -e "Remote restore log for `date`, archive name is $ARCHIVE.\n" > $LOG


#
# Now move this backup file to the appropriate location (/dump)
#
   
if [ $RESTORE_TYPE -eq 0 ]; then

    echo -e "Remote restore type is 0." >> $LOG
    echo "input args are: <$1> <$2> <$3> <$4> <$5> <$6>" >> $LOG
    # to remote (NFS/Samba) mount. Grab remaining program args from input
    SERVER=$3
    RESOURCE=$4
    FSTYPE=$5
    OPTIONS=$6
    
    # First determine if portmap is running - it should not be.
    # Then start that service for the duration of this script
    PORTMAP=/sbin/portmap
    PORTMAP_SHORT=portmap
    PID=`ps -ef | grep $PORTMAP_SHORT | grep -v grep | awk '{print $2}'`
    
    if test -n "$PID" ; then
        echo "portmap is currently executing, PID is $PID." >> $LOG
    else
        # echo No PID, so start the service.
	echo "about to start the portmap service..." >> $LOG
        /etc/init.d/portmap start
        RC=$?
        sleep 1
     
        # save away this PID for later process termination    
        NEW_PID=`ps -ef | grep $PORTMAP_SHORT | grep -v grep | awk '{print $2}'`
        
        if test -n "$NEW_PID" ; then
            echo "portmap started successfully, pid is $NEW_PID" >> $LOG
        else
            echo "unable to start the portmap daemon, rc = $RC" >> $LOG
            exit_cleanup 2
        fi
    fi
    
    copyMountToDump $DUMP_DIR $ARCHIVE $SERVER $RESOURCE $FSTYPE "$OPTIONS"
    copyRC=$?
    
    # whether the restore worked or not, we should kill the portmap service if
    # we started it.
    echo "attempt to stop the portmap service..." >> $LOG
    if test -n "$PID" ; then
        echo "portmap was running prior to script execution - not terminating the service." >> $LOG
    else
        echo "now terminating the portmap service..." >> $LOG
        kill -9 $NEW_PID
    fi
    
    if [ $copyRC -ne 0 ]; then
        exit_cleanup $copyRC
    fi
   
elif [ $RESTORE_TYPE -eq 1 ]; then

    echo -e "Remote restore type is 1." >> $LOG
    echo "input args are: <$1> <$2> <$3> <$4> <ftp_password>" >> $LOG
    # to ftp server. Grab remaining program args from input
    SERVER=$3
    USERID=$4
    PASSWORD=$5
    ftpServerToDump $DUMP_DIR $ARCHIVE $SERVER $USERID $PASSWORD
    copyRC=$?
    if [ $copyRC -ne 0 ]; then
        exit_cleanup $copyRC
    fi
    
fi


#
# That's all folks!
#
exit_cleanup 0
